﻿using ICSharpCode.SharpZipLib.Tar;
using ICSharpCode.SharpZipLib.GZip;
using System.Reflection;
using System.Text;
using System.Xml;
using HelloDict.Core;
using DictEntry = HelloDict.Core.Entry;

namespace HelloDict.Maui;

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();

    }


    private void Button_Clicked(object sender, EventArgs e)
    {

        display.Text = Word(word.Text).Definition[0];
    }
    string mainDir = FileSystem.Current.AppDataDirectory;
    public DictEntry Word(string keywords)
    {

        var entry = new DictEntry();
        XmlDocument xmlDocument = new XmlDocument();
        try
        {
            xmlDocument.Load(mainDir + $"/Dictionary/xdhycd7/{keywords}.xml");
            entry.Word = keywords;
            entry.Definition =
            [
                xmlDocument.SelectSingleNode("/Entry/Definition").InnerText
            ];
        }
        catch (FileNotFoundException)
        {
            entry.Definition = ["查无此词"];

        }
        return entry;
    }
    private async void ExtractXDHYCD()
    {
        TarArchive tarArchive;
        Stream gzipStream;

        using var stream = await FileSystem.OpenAppPackageFileAsync("xdhycd7.tar.gz");
        using (gzipStream = new GZipInputStream(stream))
        {
            tarArchive = TarArchive.CreateInputTarArchive(gzipStream, Encoding.UTF8);
            Directory.CreateDirectory(mainDir + "/Directory");
            tarArchive.ExtractContents(mainDir + "/Dictionary");
            tarArchive.Close();
        }
        
    }

    private async void ContentPage_Appearing(object sender, EventArgs e)
    {
        var status = await Permissions.CheckStatusAsync<Permissions.StorageRead>();
        if (status != PermissionStatus.Granted)
        {
            status = await Permissions.RequestAsync<Permissions.StorageRead>();
            ContentPage_Appearing(sender, e);
        }
        else
        {
            if (!Directory.Exists(mainDir+"/Dictionary/xdhycd7"))
            {
                ExtractXDHYCD();
            }
        }

    }
}

